package com.课上案例练习.线程.等待唤醒机制.线程等待.两个线程通信;

/**
 * 实现交替通信,如果不使用通信，容易尝试执行完该第一个任务又再次获取该任务
 * 所以要让任务A进入等待，然后唤醒任务B，等待另一个任务B执行完，唤醒再执行该任务A，任务B进入等待
 */
public class Show3 implements Runnable {
    int flag = 1;//标识
    Object object=  new Object();

    public Show3(int flag, Object object) {
        this.flag = flag;
        this.object = object;
    }

    @Override
    public void run() {
        if(flag==1){
            for (int i = 0; i < 3; i++) {
                synchronized (object){
                    System.out.print("我");
                    System.out.print("想");
                    System.out.print("看");
                    System.out.print("看");
                    System.out.println();
                    object.notify();//唤醒其他任务
                    try {
                        object.wait();//进入等待
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }finally {
                        object.notify();
                    }
                }
            }
        }
        else if(flag==0){
            for (int i = 0; i < 3; i++) {
                synchronized (object){
                    System.out.print("世");
                    System.out.print("界");
                    System.out.print("那");
                    System.out.print("么");
                    System.out.print("大");
                    System.out.println();
                    object.notify();
                    try {
                        object.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }
}
